""" Check permissions existance """

from sqlobject import classregistry

from mnemoply import model
from mnemoply.mass_actions import registry
from mnemoply.preorders import preorders
from mnemoply.controllers import Root

def collect_from_mass_actions():
    result = []
    for class_name in registry.actions:
        for action in registry.actions[class_name].values():
            if not action.read_only:
                result.append('%s/%s' % (class_name, action.name))
    return result

def collect_from_model_objects():
    result = []
    for cls in classregistry.registry(None).allClasses():
        if model.ModelObject in cls.mro():
            if cls.__name__ != 'ModelObject':
                result.append('%s/edit' % cls.getModelName())
    return result

def collect_from_orders():
    return ['Order:%s' % x for x in preorders.preorders.keys()]

def collect_from_list():
    return ['dba']

def collect():
    return collect_from_mass_actions() + \
        collect_from_model_objects() + \
        collect_from_orders() + \
        collect_from_list()

def check_existance():
    """
        Create root controller to import all controllers (and therefore mass actions)
    """

    Root()

    exists = set([x.permission_name for x in model.AuthPermission.select()])
    collected = set(collect())

    for name in collected - exists:
        print "Creating permission %s..." % name
        model.AuthPermission(permission_name=name)

    for name in exists - collected:
        print "Warning: obsoleted", name
